package common.core
{
	import common.manager.GLayer;
	import common.manager.GScene;
	import common.manager.GUI;
	import common.manager.keymanager.Key;
	import common.world.World;
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.text.TextField;

	/**
	 * 游戏引擎启动类
	 * @author liuyong
	 */	
	public class GEngine
	{
		static private var m_ins : GEngine; 
		static private var m_completeCallBack : Function;
		static private var m_cmdGroup : Tab;
		
		public function GEngine()
		{
		}
		
		/**
		 * 启动游戏引擎
		 * @param width   游戏宽
		 * @param height  游戏高
		 * @param root    游戏根舞台
		 */		
		static public function start(width:Number,height:Number,root:Sprite,completeCallBack:Function=null) : void
		{
			m_cmdGroup = new Tab;
						
			root.stage.align = StageAlign.TOP_LEFT;
			root.stage.scaleMode = StageScaleMode.NO_SCALE;
			
			Ins.startManager(width,height,root);	
			
			if(completeCallBack != null)
			{
				m_completeCallBack = completeCallBack;
				
				Config.build("Config.xml");
				
				Config.Instance.addEventListener(Config.INITCONFIGCOMPLET,OnLoadConfigComplete);
			}
		}
		
		static private function OnLoadConfigComplete(evt : Event) : void
		{
			Config.Instance.removeEventListener(Config.INITCONFIGCOMPLET,OnLoadConfigComplete);
			
			m_completeCallBack();
			m_completeCallBack = null;
		}
		
		/**
		 *关闭游戏引擎 
		 */		
		static public function stop() : void
		{
			Ins.stopManager();
		}
		
		/**
		 * 启动游戏管理器
		 * @param width   游戏宽
		 * @param height  游戏高
		 * @param root    游戏根舞台
		 */	
		public function startManager(width:Number,height:Number,root:Sprite) : void
		{
			GLayer.Instance.build(root);
			GScene.bulid(width,height,root);
			Key.build(GLayer.Instance.key);
			World.build(GLayer.Instance.world,1600,1000);
			GUI.build(GLayer.Instance.ui);
			GMouse.build(GLayer.Instance.mouse);
			
		}
		
		/**
		 *关闭游戏管理器
		 */	
		public function stopManager() : void
		{
			GMouse.destory();
			GUI.destory();
			World.destory();
			Key.destory();
			GScene.destory();
			GLayer.Instance.destory();
		}
		
		/**
		 * @return  GEngine单列
		 */
		static private function get Ins() : GEngine
		{
			if(!m_ins)
			{
				m_ins = new GEngine;
			}
			
			return m_ins;
		}
		
		static public function registerCMD(id:String,cmd : *) : void
		{
			m_cmdGroup.add(id,cmd);
		}
		
		static public function removeCMD(id:String) : void
		{
			m_cmdGroup.remove(id);
		}
	}
}